<?php

namespace App\Http\Model\CoolNumberShoppingMall;

use App\Exceptions\PublicException;
use App\Http\Model\Base;

/**
 * 用户靓号积分流水
 *
 * Created on 2021/12/6 13:59
 * @Author <yuxiang.zhu@asiainnovations.net>
 */
class UserScoreStream extends Base
{
    //from
    const FROM_TEST = 'test';// 测试
    const FROM_BUY_COOL_NUMBER = 'buy_cool_number';// 购买靓号

    /**
     * 表名字
     *
     * @var string
     */
    protected $table = 'cool_number_user_score_stream';

    /**
     * 指示模型是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 模型日期列的存储格式。
     *
     * @var string
     */
    protected $dateFormat = 'U';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['id', 'user_id', 'from', 'score', 'created_at', 'updated_at'];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * Created at 2021/12/6 13:54
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return string[]
     */
    public function listFrom(): array
    {
        return [
            self::FROM_TEST => '测试',
            self::FROM_BUY_COOL_NUMBER => '购买靓号',
        ];
    }

    /**
     * 记录积分变更流水
     *
     * Created at 2021/12/6 14:03
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @param string $from
     * @param int $score
     * @throws PublicException
     */
    public function add(int $userId, string $from, int $score)
    {
        if (!in_array($from, array_keys($this->listFrom()))) {
            throw new PublicException('用户靓号积分流水变更from字段未设置');
        }

        self::query()->create(['user_id' => $userId, 'from' => $from, 'score' => $score]);
    }
}